"""

Task that performs feedback on a group of individuals. This will include 
both survival and reproduction.

"""
# Import schema modules
from tasks.operators import feedback_operator
from tasks.libs import constants as sc

# Import DEXEN modules
from dexen.user.libs import constants as dc
from dexen.user.libs import server_api

""" GLOBALS """
pop_api = server_api.PopAPIFactory()

def evaluate(individuals = None):
    """
    Task that:
        - gets the number of individuals to process from the server
        - downloads individuals from the server
        - perform feedback on these individuals
        - uploads the updated individuals back to the server (some dead, some alive)
        - uploads the new individuals back to the server
    """
    print "I am in feedback" 
    
    # Get the number of individuals to be processed for the global data saved
    # on the server. These numbers are set in the config function for this 
    # schema.
    count_for_feedback = pop_api.getGlobalData()[sc.FEEDBACK]
    
    # Download individuals
    individuals = pop_api.downloadLiveIndividuals(
        select = (sc.PHENOTYPE, ), 
        where = (
            (sc.EVALUATION, dc.NOT_EQUAL, None)
        ),
        count = count_for_feedback
    )
    
    # Apply the operator to all individuals
    child_individuals = feedback_operator.executeFeedback(individuals)
    
    # Upload individuals
    pop_api.uploadIndividuals(individuals)
    pop_api.uploadIndividuals(child_individuals)


